<template>
  <div>
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
      @visible-change="handleVisibleChange"
    />
    <table-box ref="tableBox" show-index show-selection :other-filters="filtersRaw" :other-raw="paramsRaw" :table-config="tableConfig" @selection-change="handleSelectionChange" @btnOperate="handleBtnOperate" />
    <export-files
      v-if="exportisible"
      title="导出"
      :visible.sync="exportisible"
      download-url=""
      download-prefix=""
      :config="exportConfig"
      :success-fun="(config,res)=>{}"
      @success="handleExportSuccess"
    />
    <Disabled ref="disable" :rows="selectedRows" @on-success="()=>refreshTableBoxData('onPage')" />
  </div>
</template>

<script>
import { marketEnable } from '@/api/channelTask2/market'
import Disabled from './components/disable'
import { getToken } from '@/utils/auth'
export default {
  name: 'Market',
  components: {
    Disabled
  },
  props: {
  },
  data() {
    return {
      searchConfig: [
        { label: '市场编码', prop: 'marketCode', type: 'text', value: '', placeholder: '模糊查询' },
        { label: '市场名称', prop: 'marketName', type: 'text', value: '', placeholder: '模糊查询' },
        {
          label: '所属办事处',
          prop: 'agencyCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/organization/page',
            paramField: 'keyWord', // 远程搜索参数名
            filtersRaw: [{ 'id': 'isOffice', 'property': 'isOffice', 'value': '1', 'operator': '=' }],
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '所属办事处',
            interfacePath: '/select-service/api/v1/organization/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            filtersRaw: [{ 'id': 'isOffice', 'property': 'isOffice', 'value': '1', 'operator': '=' }],
            pageFlag: true
          }
        },
        {
          type: 'select',
          prop: 'marketNatrue',
          label: '市场属性',
          value: '',
          placeholder: '',
          config: {
            remote: false,
            filterable: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/MARKET_NATURE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'isAttractInvestment',
          label: '是否完成招商',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/BOOLEANS`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'dataSource',
          label: '数据来源',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_MARKET_DATA_FROM`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'select',
          prop: 'allocationStatus',
          label: '办事处任务分配状态',
          value: '',
          placeholder: '',
          config: {
            remote: true,
            // paramField: 'keyWord',// 远程搜索参数名
            remoteUrl: `/data-dict/api/v2/dictionary/CTM_ALLOCATE_STYLE`,
            defaultProps: {
              label: 'dictName',
              value: 'dictCode'
            },
            paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
            apiHeader: {
              // 'Permission-Code': 'per_pur_order_middle_page',
              // 'Permission-App': 'slm'
            }
          }
        },
        {
          type: 'radio',
          prop: 'enable',
          label: '启用状态',
          value: '',
          placeholder: '',
          config: {
            remote: false,
            defaultProps: {
              label: 'label',
              value: 'value'
            },
            selectData: [
              { label: '全部', value: '' },
              { label: '启用', value: '1' },
              { label: '停用', value: '0' }
            ]
          }
        }

      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarket/page`,
        hideSearchBar: true,
        sort: 'createTime',
        order: 'DESC',
        setting: [
          {
            prop: 'marketCode',
            label: '市场编码',
            className: 'btn-green',
            minWidth: 140,
            isButton: true,
            clickFun: this.toDetail
          },
          {
            prop: 'marketName',
            label: '市场名称',
            minWidth: 120
          },
          {
            prop: 'provinceName',
            label: '省份',
            minWidth: 100
          },
          {
            prop: 'cityName',
            label: '城市',
            minWidth: 100
          },
          {
            prop: 'districtName',
            label: '区/县',
            minWidth: 100
          },
          {
            prop: 'streetName',
            label: '街道/乡镇',
            minWidth: 130
          },
          {
            prop: 'agencyName',
            label: '所属办事处',
            minWidth: 130
          },
          {
            prop: 'isOldMerchant',
            label: '是否有老商家',
            minWidth: 130,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'marketNatrue',
            label: '市场属性',
            minWidth: 120,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'MARKET_NATURE'
            }
          },
          {
            prop: 'isAttractInvestment',
            label: '是否完成招商',
            minWidth: 130,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'dataSource',
            label: '数据来源',
            minWidth: 120,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'CTM_MARKET_DATA_FROM'
            }
          },
          {
            prop: 'allocationStatus',
            label: '办事处任务分配状态',
            minWidth: 140,
            propEnum: {
              appCode: 'slm',
              domainCode: 'marketing',
              dictTypeCode: 'CTM_ALLOCATE_STYLE'
            }
          },
          {
            prop: 'enable',
            label: '启用状态',
            minWidth: 120,
            formatData: v => {
              return [1, '1'].includes(v.enable) ? '启用' : '停用'
            }
          }
        ],
        btnList: process.env.NODE_ENV === 'development' ? [
          { buttonName: '新增', optCode: 'add', outerFlag: true },
          { buttonName: '编辑', optCode: 'edit', outerFlag: true },
          { buttonName: '导出', optCode: 'export', outerFlag: true },
          { buttonName: '停用', optCode: 'disable', outerFlag: true },
          { buttonName: '启用', optCode: 'enable', outerFlag: true }
        ] : null
      },
      exportisible: false,
      selectedRows: [],
      filtersRaw: [],
      paramsRaw: {}
    }
  },
  computed: {
    exportConfig() {
      return [
        {
          code: '1',
          name: '市场管理',
          async: false, // 同步导出数据
          templateCode: '', // 模板code
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/ctmMarket/export`, // 数据导出api
          headers: { token: getToken() },
          filtersRaw: this.filtersRaw, // 符合当前查询条件的所有数据行的导出条件(当前数据查询结果对应的条件)
          paramsRaw: this.paramsRaw,
          sort: 'createTime', // 排序字段
          order: 'desc', // 排序方式
          selectedRows: this.selectedRows, // 当前所选中的数据行
          queryField: 'id'// 指定行导出时使用的查询字段名称
        }
      ]
    }
  },
  methods: {
    clearSearch() {
      this.filtersRaw = []
      this.paramsRaw = {}
    },
    handleSearch({ filtersRaw, paramsRaw }) {
      this.filtersRaw = filtersRaw
      this.paramsRaw = paramsRaw
      this.refreshTableBoxData()
    },
    handleVisibleChange() {
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.refreshTableHeight()
      })
    },
    refreshTableBoxData(flag) {
      this.$nextTick(() => {
        this.$refs.tableBox.initTableData(flag)
      })
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleBtnOperate(flag) {
      this[flag] && this[flag]()
    },
    add() {
      this.$pageStack.push('src/views/channelTask2/attractInvestment/market/addEdit.vue', {
        props: {
          isAttractInvestmentTeam: true
        }
      }, (flag) => {
        flag && this.refreshTableBoxData(flag)
      })
    },
    edit() {
      if (!this.singleJudge(this.selectedRows, '编辑', true)) {
        return
      }
      // “办事处任务分配状态”值为“已分配”的数据不允许编辑；是否完成招商为“是”的数据，不允许编辑
      // if (this.selectedRows[0].allocationStatus === 'B') {
      //   this.$message.warning('办事处任务分配状态为【已分配】的数据不能编辑!')
      //   return
      // }
      // if ([1, '1'].includes(this.selectedRows[0].isAttractInvestment)) {
      //   this.$message.warning('是否完成招商为【是】的数据不能编辑!')
      //   return
      // }
      // 编辑：“办事处任务分配状态”值为“已分配”的数据不允许编辑；是否完成招商为“是”的数据，不允许编辑；

      // 40742   【待开发及整改市场管理】编辑功能控制调整
      // 【招商管理-空白市场】编辑功能控制调整
      // 1.调整前：“办事处任务分配状态”值为“已分配”的数据不允许编辑；
      // 是否完成招商为“是”的数据，不允许编辑；调整后：只控制是否完成招商为“是”的数据，不允许编辑
      if ([1, '1'].includes(this.selectedRows[0].isAttractInvestment)) {
        this.$message.warning('是否完成招商为【是】的数据不能编辑!')
        return
      }
      this.$pageStack.push('src/views/channelTask2/attractInvestment/market/addEdit.vue', {
        props: {
          id: this.selectedRows[0].id
        }
      }, (flag) => {
        flag && this.refreshTableBoxData(flag)
      })
    },
    toDetail(row) {
      this.$pageStack.push('src/views/channelTask2/attractInvestment/market/detail.vue', {
        props: {
          id: row.id
        }
      })
    },
    export() {
      this.exportisible = true
    },
    disable() {
      if (!this.singleJudge(this.selectedRows, '停用', true)) {
        return
      }
      const d = this.selectedRows[0]
      if ([0, '0'].includes(d.enable)) {
        this.$message.warning('已停用市场不能操作!')
        return
      }
      if (d.dataSource !== 'D') {
        this.$message.warning('只能停用数据来源为【招商团队】的数据!')
        return
      }
      if ([1, '1'].includes(d.isAttractInvestment)) {
        this.$message.warning('不能停用是否完成招商为【是】的数据!')
        return
      }
      this.$refs.disable.openDialog()
    },
    enable() {
      if (!this.singleJudge(this.selectedRows, '启用')) {
        return
      }
      if (!this.selectedRows.every(e => e.dataSource === 'D')) {
        this.$message.warning('只能启用数据来源为【招商团队】的数据!')
        return
      }
      if (!this.selectedRows.every(e => [0, '0'].includes(e.enable))) {
        this.$message.warning('所选项包含【启用】数据!')
        return
      }
      // 只能启用数据来源为“招商团队”的数据
      this.$msgbox({
        title: '启用',
        message: `<div>将启用<span style="color:red;">${this.selectedRows.length}</span>条数据？</div>`,
        showCancelButton: true,
        dangerouslyUseHTMLString: true
      }).then(() => {
        return marketEnable(this.selectedRows.map(e => e.id)).then(res => {
          this.$message.success('操作成功!')
          this.refreshTableBoxData('onPage')
        })
      })
    },
    handleExportSuccess() {

    }
  }
}
</script>
